import { ConnectionConfig } from "mysql";
import { getLogger } from "maishu-node-mvc"
import { projectName } from "./website-config";
import { getConnectionManager, ConnectionOptions, createConnection, getConnection, EntityManager, Repository } from "typeorm";
import path = require("path");
import fs = require("fs");
import { WeiXinSetting, User } from "./entities";

export class WeiXinDataContext {

    private entityManager: EntityManager;
    settings: Repository<WeiXinSetting>;
    user: Repository<User>;

    constructor(entityManager: EntityManager) {
        this.entityManager = entityManager;
        this.settings = this.entityManager.getRepository(WeiXinSetting);
        this.user = this.entityManager.getRepository(User);
    }
}

export async function createDataContext(connConfig: ConnectionConfig): Promise<WeiXinDataContext> {
    let logger = getLogger(`${projectName}:${createDataContext.name}`);
    let connectionManager = getConnectionManager();
    if (connectionManager.has(connConfig.database) == false) {
        let entitiesPath = path.join(__dirname, "entities.js");
        if (!fs.existsSync(entitiesPath)) {
            logger.error(`Entities path is not exists, path is ${entitiesPath}.`);
        }

        let entities: string[] = [entitiesPath];
        let dbOptions: ConnectionOptions = {
            type: "mysql",
            host: connConfig.host,
            port: connConfig.port,
            username: connConfig.user,
            password: connConfig.password,
            database: connConfig.database,
            synchronize: true,
            logging: false,
            connectTimeout: 3000,
            entities,
            name: connConfig.database
        }

        await createConnection(dbOptions);
    }

    let connection = getConnection(connConfig.database);
    let dc = new WeiXinDataContext(connection.manager);
    return dc;
}